package com.example.administrator.myapplication;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class ReadContectActivity extends AppCompatActivity {
    private final int PERMISSION_REQUEST_CODE = 1;
    TextView contactsText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_contect);
        contactsText = (TextView) findViewById(R.id.contactsText);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    ReadContectActivity.this, new String[]{
                            Manifest.permission.READ_CONTACTS}, PERMISSION_REQUEST_CODE);
                    }
                    else{
            contactsText.setText(getQueryData());
        }

    }
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,
              int[] grantResults){
        switch(requestCode){
            case PERMISSION_REQUEST_CODE:
                if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    contactsText.setText(getQueryData());
                }
                else{
                    Toast.makeText(this, "你没有同意授权", Toast.LENGTH_SHORT).show();

                }
                break;
            default:
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    private CharSequence getQueryData() {
        StringBuilder string = new StringBuilder("联系人清单\n");
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            String displayName = cursor.getString(displayNameIndex);
            string.append(" - " + displayName + "\n");
        }
        cursor.close();
        return string.toString();
    }
}
